package purchase;

import java.awt.*;
import java.util.Scanner;

public class BuyTicketThread implements Runnable{
    private RailwayStation railwayStation = new RailwayStation();//即所有的线程都可以访问这个购票系统

    private void saleTicket(int numTickets){
        synchronized (railwayStation){//要让同步代码块获得对象的锁才可以进行购票
            if (railwayStation.getTickets() > 0) {
                try {
                    Thread.sleep(10);
                    System.out.println(Thread.currentThread().getName() + "开始售票");
                    railwayStation.sale(numTickets);
                    System.out.println(Thread.currentThread().getName() + "售票完成");
                    System.out.println("票数：" + railwayStation.getTickets());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }else{
                System.out.println("对不起！票数不够了");
                System.exit(1);
            }
        }
    }
    @Override
    public void run() {
        //Scanner input = new Scanner(System.in);
        for (int i = 0;railwayStation.getTickets() > 0;i++) {
            System.out.println(Thread.currentThread().getName() + " " + (i + 1));
            saleTicket(1);
        }
        //System.out.print("请输入购票张数：");
    }
}
